package com.heima.leadnews.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.leadnews.wemedia.mapper.WmMaterialMapper;
import com.heima.leadnews.wemedia.service.WmMaterialService;
import com.heima.leadnews.wemedia.service.WmNewsMaterialService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmMaterialDTO;
import com.heima.model.wemedia.pojo.WmMaterial;
import com.heima.model.wemedia.pojo.WmNewsMaterial;
import com.heima.utils.common.UserContext;
import com.jlefebure.spring.boot.minio.MinioException;
import com.jlefebure.spring.boot.minio.MinioService;
import org.apache.commons.io.FilenameUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 自媒体图文素材信息表 服务实现类
 *
 * @author author
 * @since 2023-06-03
 */
@Service
@RefreshScope
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private MinioService minioService;

    @Value("${spring.minio.url}")
    private String minioUrl;

    @Value("${spring.minio.bucket}")
    private String bucket;;

    @Autowired
    private WmNewsMaterialService newsMaterialService;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) throws IOException, MinioException {
        if (multipartFile == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //1.将前端上传的图片保存到minio
        //1.1生成文件名

        String uuid = UUID.randomUUID().toString();
        //1.2获取前端上传文件的原始名称
        String originalFilename = multipartFile.getOriginalFilename();
        //1.3获取扩展名
        String extension = FilenameUtils.getExtension(originalFilename);
        String name = uuid + extension;
        ContentType type = getImageContentType(extension);
        minioService.upload(Paths.get(name)
                , multipartFile.getInputStream()
                , type);
        //2.调用mapper将素材的信息保存到wm_material
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(UserContext.getUserId().intValue());
        String url = minioUrl + "/" + bucket + "/" + name;
        wmMaterial.setUrl(url);
        wmMaterial.setType(Boolean.FALSE);
        wmMaterial.setIsCollection(Boolean.FALSE);
        wmMaterial.setCreatedTime(LocalDateTime.now());
        save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }


    /**
     * 分页查询我的素材  条件 我的素材，是否收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult pager(WmMaterialDTO dto) {
        dto.checkParam();
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        //userId等于当前登陆人id
        queryWrapper.eq(WmMaterial::getUserId, UserContext.getUserId())
                .orderByDesc(WmMaterial::getCreatedTime);
        //判断是否查询已收藏的图片
        if (dto.getIsCollection() != null && dto.getIsCollection() == WmMaterial.CollectionStatus.COLLECTION) {
            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //执行分页查询
        page(page, queryWrapper);
        //封装结果返回
        return PageResponseResult.okResult(dto.getPage(), dto.getSize()
                , page.getTotal(), page.getRecords());
    }

    /**
     * 收藏素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //可以修改其他用户素材的状态
        if (wmMaterial.getUserId().longValue() != (UserContext.getUserId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wmMaterial.setIsCollection(!wmMaterial.getIsCollection());
        updateById(wmMaterial);
        return ResponseResult.okResult();
    }

    /**
     * 删除素材图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) throws MinioException {
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //可以修改其他用户素材的状态
        if (wmMaterial.getUserId().longValue() != (UserContext.getUserId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getMaterialId, id);
        int count = newsMaterialService.count(queryWrapper);
        if (count > 0) {
            //文章已经被使用
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //删除素材信息
        removeById(id);
        //删除minio中的图片
        String name = FilenameUtils.getName(wmMaterial.getUrl());
        minioService.remove(Paths.get(name));
        return ResponseResult.okResult();
    }

    /**
     * 根据扩展名，获取文件的类型ContentType
     *
     * @param extension
     * @return
     */
    public static ContentType getImageContentType(String extension) {
        Map<String, ContentType> map = new HashMap<>();
        map.put("jpg", ContentType.IMAGE_JPEG);
        map.put("png", ContentType.IMAGE_PNG);
        map.put("gif", ContentType.IMAGE_GIF);
        map.put("bmp", ContentType.IMAGE_BMP);
        return map.get(extension);
    }
}

